import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../service/service_methods.dart';
import '../model/category.dart';
import '../model/categoryGoodsList.dart';
import '../provider/child_category.dart';
import '../provider/category_goods_list.dart';
import '../routes/application.dart';


class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(title: Text('分类页面'),),
        body: Row(
          children: <Widget>[
            LeftCategoryNav(),
            Column(
              children: <Widget>[
                RightCategoryNav(),
                CategoryGoodsList(),
              ],
            ),
          ],
        ),
      ),
    );

  }
}

class LeftCategoryNav extends StatefulWidget {
  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List list = [];

  @override
  void initState() {
    _getCategory();
    _getGoodsList('');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
        border: Border(
          right: BorderSide(width: 0.5, color: Colors.black12)
        )
      ),
      child: ListView.builder(
        itemCount: list.length, 
        itemBuilder: (context, index){
          return _leftInkWell(index);
        },
      ),
    );
  }

  
  void _getCategory() async {
    await request('getCategory').then((val) {
      var data = json.decode(val.toString());
      CategoryBigListModel category = CategoryBigListModel.fromJson(data['data']);
      Provider.of<ChildCategory>(context, listen: false).updateChildCategoryList(category.data[0].bxMallSubDto, category.data[0].mallCategoryId);
      setState(() {
        list = category.data;
      });
    });
  }

  // 分类子项
  Widget _leftInkWell(int index) {
    return InkWell(
      onTap: (){
        Provider.of<ChildCategory>(context, listen: false).updateChildCategoryList(list[index].bxMallSubDto, list[index].mallCategoryId);
        // print(Provider.of<ChildCategory>(context, listen: false).list);
        _getGoodsList('');
      },
      child: Consumer<ChildCategory>(
        builder: (context, ChildCategory childCategory, child) {
          return Container(
            height: ScreenUtil().setHeight(100),
            padding: EdgeInsets.only(left: 10.0, top: 20.0),
            decoration: BoxDecoration(
              color: childCategory.categoryId==list[index].mallCategoryId ? Color.fromRGBO(235, 235, 235, 1.0) : Colors.white,
              border: Border(
                bottom: BorderSide(width: 0.5, color: Colors.black12)
              )
            ),
            child: child,
          );
        },
        child: Text(list[index].mallCategoryName, style: TextStyle(fontSize: ScreenUtil().setSp(28)),),
      ),
    );
  }

  void _getGoodsList(String categorySubId) {
    var data = {
      'categoryId': Provider.of<ChildCategory>(context, listen: false).categoryId,
      'categorySubId': Provider.of<ChildCategory>(context, listen: false).subId,
      'page': Provider.of<ChildCategory>(context, listen: false).page
    };
    request('getMallGoods', formData: data).then((val){
      var data = json.decode(val.toString());
      // setState(() {
      //   list = CategoryGoodsListModel.fromJson(data).data;
      // });
      // 存储到provider
      Provider.of<CategoryGoodsListProvider>(context, listen: false).changeCategoryGoodsList(CategoryGoodsListModel.fromJson(data).data);
      // print('商品列表数据：$data');
    });
  }
}

// 右侧小分类
class RightCategoryNav extends StatefulWidget {
  @override
  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(570),
      height: ScreenUtil().setHeight(80),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.black12, width: 0.5))
      ),
      child: Consumer<ChildCategory>(
        builder: (context, ChildCategory childCategoryList, child) => ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: childCategoryList.list.length,
          itemBuilder: (context, index) => _rightInkWell(childCategoryList.list[index], index, childCategoryList.childIndex),
        ),
      )
    );
  }

  // 分类子项
  Widget _rightInkWell(BxMallSubDto item, int currentIndex, int childIndex) {
    return InkWell(
      onTap: (){
        Provider.of<ChildCategory>(context, listen: false).changeChildIndex(currentIndex, item.mallSubId);
        _getGoodsList();
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item.mallSubName,
          style: TextStyle(
            color: currentIndex == childIndex ? Colors.pink : Colors.black,
            fontSize: ScreenUtil().setSp(28)
          ),
        ),
      ),
    );
  }

  void _getGoodsList() {
    var data = {
      'categoryId': Provider.of<ChildCategory>(context, listen: false).categoryId,
      'categorySubId': Provider.of<ChildCategory>(context, listen: false).subId,
      'page': Provider.of<ChildCategory>(context, listen: false).page
    };
    request('getMallGoods', formData: data).then((val){
      var data = json.decode(val.toString());
      // setState(() {
      //   list = CategoryGoodsListModel.fromJson(data).data;
      // });
      // 存储到provider
      var list = CategoryGoodsListModel.fromJson(data).data;
      if(list == null) {
        list = [];
      }
      Provider.of<CategoryGoodsListProvider>(context, listen: false).changeCategoryGoodsList(list);
      // print('商品列表数据：$data');
    });
  }
}

// 商品列表
class CategoryGoodsList extends StatefulWidget {
  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {
  // List<CategoryListData> list = [];
  // 初始化listview控制器
  var scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        width: ScreenUtil().setWidth(570),
        child: Consumer2<CategoryGoodsListProvider, ChildCategory>(
          builder: (context, CategoryGoodsListProvider categoryGoodsList, ChildCategory childCategory, child) {
            if(categoryGoodsList.list.length > 0) {
              try {
                if(childCategory.page == 1) {
                  scrollController.jumpTo(0.0);
                }
              } catch(e) {
                print('进入页面第一次初始化:$e');
              }
              return EasyRefresh(
                controller: childCategory.easyRefreshController,
                onLoad: () async{
                  print('开始加载更多...');
                  await _getMoreGoodsList();
                },
                enableControlFinishLoad: false,
                topBouncing: false,
                footer: ClassicalFooter(
                  noMoreText: childCategory.noMoreText,
                  loadText: '上拉加载更多',
                  loadingText: '数据加载中...',
                  loadedText: '加载完成',
                  textColor: Colors.pink,
                  showInfo: false
                ),
                child: ListView.builder(
                  controller: scrollController,
                  itemCount: categoryGoodsList.list.length,
                  itemBuilder: (context, index) => _listItem(categoryGoodsList.list[index]),
                ),
              );
            } else {
              return Center(child: Text('暂无数据'),);
            }
          },
        ),     
      )
    );
  }

  // 上拉加载更多
  Future _getMoreGoodsList() async {
    Provider.of<ChildCategory>(context, listen: false).addPage();
    var data = {
      'categoryId': Provider.of<ChildCategory>(context, listen: false).categoryId,
      'categorySubId': Provider.of<ChildCategory>(context, listen: false).subId,
      'page': Provider.of<ChildCategory>(context, listen: false).page
    };
    return request('getMallGoods', formData: data).then((val){
      var data = json.decode(val.toString());
      // 存储到provider
      var list = CategoryGoodsListModel.fromJson(data).data;
      if(list == null) {
        Fluttertoast.showToast(
          msg: '没有更多数据了！',
          toastLength: Toast.LENGTH_LONG,
          timeInSecForIos: 1,
          gravity: ToastGravity.CENTER,
          backgroundColor: Color.fromRGBO(245, 245, 245, 1),
          textColor: Colors.pink,
          fontSize: ScreenUtil().setSp(28.0)
        );
        Provider.of<ChildCategory>(context, listen: false).changeNoMore('没有更多数据了...');
      } else {
        Provider.of<CategoryGoodsListProvider>(context, listen: false).changeCategoryGoodsList(list, add: true);
      }
    });
  }

  // 商品列表页子项图片
  Widget _goodsImage(String image) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(image),
    );
  }

  // 商品名称
  Widget _goodsName(String name) {
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        name,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  // 商品价格
  Widget _goodsPrice(CategoryListData item) {
    return Container(
      margin: EdgeInsets.only(top: 20),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text(
            '价格：￥${item.presentPrice}',
            style: TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            '￥${item.oriPrice}',
            style: TextStyle(color: Colors.black26, decoration: TextDecoration.lineThrough),
          ),
        ],
      ),
    );
  }

  // 商品列表子项合成
  Widget _listItem(CategoryListData item) {
    return InkWell(
      onTap: (){
        Application.router.navigateTo(context, '/details?id=${item.goodsId}');
      },
      child: Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(color: Colors.black12, width: 0.5)
          )
        ),
        child: Row(
          children: <Widget>[
            _goodsImage(item.image),
            Column(
              children: <Widget>[
                _goodsName(item.goodsName),
                _goodsPrice(item)
              ],
            ),
          ],
        ),
      ),
    );
  }
}